//菜单管理页面
import React,{ useState, useEffect } from 'react';
import {
  ReloadOutlined, FormOutlined,
  PlusSquareOutlined, EditOutlined} from '@ant-design/icons';
import { Row,Col,Button, Spin ,Pagination,Popconfirm, notification,Alert   } from 'antd';
import useStore from '../../components/useStore.js'
import {
  openNotification_util} from '../../components/ship/util/util.js'
var storage = window.localStorage;
import Sortable from '../../components/ship/newmes/sortable.js';
import { use_bgcd_initcolmun } from '../../components/ship/sys/use_sys_config.js';
import request from '../../untils/request.js';

const Menu = () => {

    const [isloading, setisloading] = useState(false)
    const [initSize, setinitSize] = useState() //table宽度大小
    const [ifshow, setifshow] = useState(true)
    const [listdata, setlistdata] = useState([])
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [columnarr, setcolumnarr] = useState(use_bgcd_initcolmun)
    const { setnowroute,collapsed } = useStore();
    const [currentPage,setcurrentPage] = useState(1)//当前页
    const [total,settotal] = useState(10)//总数

    useEffect(() => {
        querylist()
    }, [])

    useEffect(() => { ifshow ? "" : setifshow(true) }, [ifshow])

    //菜单查询
    const querylist = async () => {
        setisloading(true)
        let rtdata = await request("/admin/menu/selectMenus", {
            method: "POST",
            mode: 'cors', // 保留跨域配置
            body:{
                pageSize:10,
                offset:(currentPage-1)*10
            }
        })
        setlistdata(rtdata.data)
        settotal(rtdata.total)
        setifshow(false)
        setisloading(false)
    }

    /**手动查询*/
    const handleQuery = async () => {
        querylist()
    }

    /**新增*/
    const handleadd = async () => {
        setnowroute({...{route:"/ship/sys/addMenuForm",title:"新增左侧菜单"}})
    }

    const editMenu=(id)=>{//点击编辑菜单按钮
        setnowroute({...{route:"/ship/sys/editMenuForm?id="+id,title:"编辑菜单"}})
    }

    const deleteMenu = (e)=>{//删除菜单
        request("/admin/menu/delete", {
            method: 'POST',
            mode: 'cors', // 保留跨域配置
            body: { 
                menu_id: e // 只需传入菜单ID，操作者ID从token获取
            }
        })
        .then(data => {
            if (data.code === 200) {
                notification.success({
                    message: data.msg
                });
            } else {
                notification.error({
                    message: data.msg
                });
                querylist(); // 刷新菜单列表
            }
        })
        .catch(() => {
            notification.error({
                message: "删除失败",
                description: "无法删除菜单，请稍后重试"
            });
        });
    }

    const changePage=(e)=>{//改变当前页
        setcurrentPage(e)
    }

    useEffect(()=>{
        querylist()
    },[currentPage])

    return (
        <div style={{    
            maxHeight:"90vh",
            backgroundColor: `#F1F1F1`,
            right:"1%",
            top:"6vh",
            overflowY:"scroll",
            overflowX:"hidden",
            width: collapsed?"94%":"84%", 
            position: "absolute",  
            color: "white", 
            fontSize: "0.8rem"
        }}>
            <div style={styles.kshcontainer}>
                <div style={{
                    width: "100%", 
                    maxWidth: "99vw",
                    height: "100%",
                    backgroundColor: "white", 
                    overflowX: "auto", 
                    margin: "0.5vw",
                    padding: "1vw",
                    borderRadius: "4px",
                    boxSizing: "border-box"
                }}>
                <div style={styleobj.linestyleflex}>
                    &nbsp;<Button 
                        style={{ 
                            backgroundColor: "white", 
                            color: "#156ef3", 
                            fontWeight: "800",
                            border: "1px solid #156ef3d8"
                        }}
                        onClick={() => { isloading ? openNotification_util("请等待数据查询完成再操作！") : handleQuery() }}
                    >
                    <ReloadOutlined />刷新</Button>
                    
                    &nbsp;<Button 
                        style={{ 
                            backgroundColor: "white", 
                            color: "#156ef3", 
                            fontWeight: "800",
                            border: "1px solid #156ef3d8"
                        }}
                        onClick={handleadd}
                    >
                    <PlusSquareOutlined />新 增</Button>
                    
                    &nbsp;<Button 
                        style={{ 
                            backgroundColor: "#156ef3d8", 
                            color: "white", 
                            fontWeight: "800",
                            border: "1px solid #156ef3d8"
                        }}
                        onClick={()=>{
                            setnowroute({...{route:"/ship/sys/role",title:"角色管理"}})  
                        }}
                    >
                    <EditOutlined /> 跳转角色 </Button>
                </div>
                
                <Alert 
                    style={{
                        width: "100%",
                        margin: "10px 0"
                    }} 
                    message="提示：删除一级菜单，其所对应的二级菜单也将全部删除！！！" 
                    type="warning" 
                    closable
                />
                
                {ifshow && <Sortable 
                    tableColnum={columnarr} 
                    handleTableColomn={(data) => { setcolumnarr(data); }}
                    storageName={"Pc_bgcd_list"} 
                    open={isModalOpen} 
                    handleOpen={(data) => { setIsModalOpen(data); }}
                    initSize={initSize} 
                    handleInitSize={(data) => { 
                        setinitSize(data); 
                        storage['Pc_bgcd_list_initsize'] = data; 
                    }}
                />}
                
                {isloading ?
                    (<div style={{ 
                        width: "100%", 
                        height: "70vh", 
                        display: "flex",
                        justifyContent: "center",
                        alignItems: "center"
                    }}>
                        <Spin tip="加载中..." size="large" />
                    </div>)
                    :
                    (<div style={{display: 'flex', flexDirection: 'column', height: 'calc(100% - 60px)'}}>
                        <Row style={{
                            width:"100%",
                            backgroundColor:'#156ef3d8',
                            color:'white',
                            marginTop:"1vh",
                            padding: "8px 0",
                            borderRadius: "4px 4px 0 0"
                        }} gutter={24}>
                            <Col span={2}>序号</Col>
                            <Col span={6}>菜单名称</Col>
                            <Col span={6}>路径</Col>
                            <Col span={6}>父级菜单</Col>
                            <Col span={4}>操作</Col>
                        </Row>
                        <div style={{
                            flex: 1,
                            overflowY: "auto",
                            overflowX: "hidden",
                            paddingRight: "10px",
                            marginTop: "8px"
                        }}>
                        {listdata.length > 0 ? (
                            listdata.map((item, index) => {
                                const isEvenRow = index % 2 === 0;
                                const isDisabled = item.is_sys === 1;
                                return (
                                <Row
                                    key={index}
                                    style={{
                                        width: "100%",
                                        marginTop: "0.5vh",
                                        borderBottom: "1px solid #eee",
                                        padding: "8px 0",
                                        backgroundColor: isEvenRow ? "#f9fafb" : "#ffffff",
                                        transition: "background-color 0.2s ease"
                                    }}
                                    onMouseEnter={(e) => {
                                        e.currentTarget.style.backgroundColor = "#f0f7ff";
                                    }}
                                    onMouseLeave={(e) => {
                                        e.currentTarget.style.backgroundColor = isEvenRow ? "#f9fafb" : "#ffffff";
                                    }}
                                    gutter={24}
                                >
                                    <Col span={2}>{index + 1 + (currentPage - 1) * 10}</Col>
                                    <Col span={6} style={{ whiteSpace: "normal", wordBreak: "break-all" }}>{item.title}</Col>
                                    <Col span={6} style={{ whiteSpace: "normal", wordBreak: "break-all" }}>{item.path}</Col>
                                    <Col span={6} style={{ whiteSpace: "normal", wordBreak: "break-all" }}>{item.parentMenu?.title || '无'}</Col>
                                    <Col span={4}>
                                    <Button 
                                        icon={<FormOutlined />} 
                                        onClick={() => editMenu(item.id)} 
                                        disabled={isDisabled} 
                                        style={{ 
                                            marginRight: '8px',
                                            color: isDisabled ? '#b0b0b0' : "#156ef3",
                                            borderColor: isDisabled ? '#d9d9d9' : "#156ef3d8",
                                            backgroundColor: isDisabled ? '#f5f5f5' : 'white',
                                            cursor: isDisabled ? 'not-allowed' : 'pointer',
                                            opacity: isDisabled ? 0.7 : 1
                                        }}
                                    >
                                        编辑
                                    </Button>
                                    <Popconfirm
                                        title="菜单删除警告，如果您不是系统的开发人员，请勿进行此操作！"
                                        okText="确认删除"
                                        cancelText="取消"
                                        onConfirm={() => deleteMenu(item.id)}
                                    >
                                        <Button 
                                            danger 
                                            disabled={isDisabled}
                                            style={{
                                                backgroundColor: isDisabled ? '#f5f5f5' : "#ff4d4f",
                                                borderColor: isDisabled ? '#d9d9d9' : "#ff4d4f",
                                                color: isDisabled ? '#b0b0b0' : 'white',
                                                cursor: isDisabled ? 'not-allowed' : 'pointer',
                                                opacity: isDisabled ? 0.7 : 1
                                            }}
                                        >
                                            删除
                                        </Button>
                                    </Popconfirm>
                                    </Col>
                                </Row>
                                );
                            })
                        ) : (
                            <div style={{
                                height: "100%",
                                display: "flex",
                                justifyContent: "center",
                                alignItems: "center",
                                color: "#666"
                            }}>
                                暂无数据
                            </div>
                        )}
                        </div>
                        <div style={{
                            marginTop: "15px",
                            textAlign: "right",
                            padding: "10px",
                            boxSizing: "border-box"
                        }}>
                            <Pagination 
                                current={currentPage}
                                onChange={changePage}
                                total={total}
                                showSizeChanger={false}
                            />
                        </div>
                    </div>)
                }
                </div>
            </div>
        </div>
    )
}

export default Menu

var styles = {
    maincontainer: {
        height: "100vh", 
        backgroundColor: `#F1F1F1`,
        backgroundSize: "100% 100%", 
        width: "100%", 
        position: "absolute", 
        left: "0", 
        color: "white", 
        fontSize: "0.8rem"
    },
    topcontainer: {
        width: "100%", 
        height: "10vw", 
        backgroundImage: "linear-gradient(to bottom,#e4e9eb , white)", 
        paddingTop: "3vw",
        position: "relative", 
        fontSize: "0.89rem", 
        textIndent: "2rem", 
        fontWeight: "800", 
        color: "#156ef3", 
        borderRadius: "0 0 15px 15px"
    },
    butdcstyle: { 
        paddingLeft:"1.5vw",
        paddingRight:"1.5vw", 
        height: "2vw", 
        position: "absolute", 
        right: "1%", 
        top: "0%", 
        backgroundColor: "#156ef3d8", 
        fontSize: "0.8vw", 
        borderRadius: "0 0 0.3vw 0.3vw" 
    },
    butmainstyle: { 
        paddingLeft:"1.5vw",
        paddingRight:"1.5vw", 
        height: "2vw", 
        position: "absolute", 
        right: "8%", 
        top: "0%", 
        backgroundColor: "#156ef3d8", 
        fontSize: "0.8vw", 
        borderRadius: "0 0 0.3vw 0.3vw" 
    },
    kshcontainer: {
        width: "100%", 
        height: "100%",
        position: "relative", 
        backgroundColor: "#F1F1F1",
        color: "black",
        boxSizing: "border-box"
    },
}
var styleobj = {
    linestyle: { 
        height: "1.8rem", 
        fontSize: "0.7rem", 
        position: "relative", 
        width: "100%", 
        textIndent: "1rem" 
    },
    linestylesmall: { 
        height: "1.3rem", 
        fontSize: "0.7rem", 
        position: "relative", 
        width: "100%", 
        textIndent: "1rem" 
    },
    linestyleflex: {
        height: "1.8rem", 
        fontSize: "0.6rem", 
        position: "relative", 
        width: "100%", 
        display: "flex", 
        justifyContent: "flex-start", 
        alignItems: "center", 
        marginBottom: "0.5rem",
        marginTop:"0.5rem"
    },
    linestyleflexitem: {
        height: "1.6rem", 
        position: "relative", 
        width: "23%", 
        textIndent: "0.5rem",
        backgroundColor: "white", 
        lineHeight: "1.6rem", 
        fontSize: "0.75rem", 
        fontWeight: "500", 
        textAlign: "center"
    },
    linestyleflexitemleft: { 
        backgroundColor: "#F0F0F0", 
        position: "absolute", 
        width: "35%", 
        left: "0" 
    },
    linestyleflexitemright: {
        backgroundColor: "white", 
        position: "absolute", 
        width: "64%", 
        right: "0" 
    },
    lineleft: { 
        width: "100%", 
        height: "100%", 
        position: "absolute", 
        left: "0%", 
        textAlign: "left", 
        lineHeight: "2rem", 
        fontSize: "0.75rem", 
        fontWeight: "700" 
    },
}
